import 'package:flutter/material.dart';
import 'package:flutter/scheduler.dart';
import 'package:flutter_chat_ui/pages/onnx/input_widgets/onnx_talk_bar_tools_view.dart';
import 'package:flutter_chat_ui/pages/onnx/llm_utils/llm_record.dart';
import 'package:flutter_chat_ui/pages/onnx/llm_utils/llm_utils.dart';
import 'package:flutter_chat_ui/pages/onnx/onnx_widgets_notifier_controller.dart';
import 'package:flutter_chat_ui/utils/performance_monitor.dart';
import 'package:flutter_chat_ui/utils/x_toast.dart';
import 'package:get/get.dart';

class OnnxChatPage extends StatefulWidget {
  const OnnxChatPage({super.key});

  @override
  State<OnnxChatPage> createState() => _OnnxChatPageState();
}

class _OnnxChatPageState extends State<OnnxChatPage> {
  final ValueNotifier<bool> _isRespondingNotifier = ValueNotifier<bool>(false);
  final ValueNotifier<bool> _isInitializingNotifier = ValueNotifier<bool>(false);

  /// 语音识别

  @override
  void initState() {
    super.initState();
    Get.put(OnnxWidgetsNotifireController());
    // 配置toast
    XToast.setToastConfig();

    // 延迟初始化，确保页面先渲染完成
    WidgetsBinding.instance.addPostFrameCallback((_) {
      // 使用SchedulerBinding确保在空闲时执行初始化
      SchedulerBinding.instance.addPostFrameCallback((_) {
        _initializeRecognizerAsync();
      });
    });
  }

  @override
  void dispose() {
    // 清理ValueNotifier
    _isRespondingNotifier.dispose();
    _isInitializingNotifier.dispose();

    // 清理GetX控制器
    if (Get.isRegistered<OnnxWidgetsNotifireController>()) {
      Get.delete<OnnxWidgetsNotifireController>();
    }

    // 确保释放LLMUtils资源
    LLMUtils().dispose();
    LLMRecord().dispose();

    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('ONNX Chat')),
      body: Stack(
        children: [
          // 主要内容
          Column(
            children: [
              /// 内容部分
              Expanded(
                child: Container(
                  color: Colors.white,
                  child: const Center(
                    child: Text(
                      '聊天内容区域',
                      style: TextStyle(
                        fontSize: 20,
                        color: Colors.black54,
                      ),
                    ),
                  ),
                ),
              ),

              /// 输入部分
              ValueListenableBuilder<bool>(
                valueListenable: _isInitializingNotifier,
                builder: (context, isInitializing, child) {
                  return OnnxTalkBarToolsView(
                    isResponding: _isRespondingNotifier,
                    isDisabled: isInitializing,
                  );
                },
              ),
            ],
          ),

          // 加载遮罩
          ValueListenableBuilder<bool>(
            valueListenable: _isInitializingNotifier,
            builder: (context, isInitializing, child) {
              if (!isInitializing) return const SizedBox.shrink();

              return const Center(
                child: CircularProgressIndicator(strokeWidth: 3.0),
              );
            },
          ),
        ],
      ),
    );
  }

  /// 异步初始化语音识别器，避免阻塞UI线程
  Future<void> _initializeRecognizerAsync() async {
    _isInitializingNotifier.value = true;
    await Future.delayed(const Duration(seconds: 1));

    try {
      await _performInitializationWithProgressUpdates();
      XToast.showSuccess('模型配置初始化成功');
    } catch (e) {
      XToast.showError('模型配置初始化失败: $e');
    } finally {
      _isInitializingNotifier.value = false;
    }
  }

  /// 在后台执行初始化操作，定期更新UI
  Future<void> _performInitializationWithProgressUpdates() async {
    await PerformanceMonitor.measureAsync('录音初始化', () async {
      await LLMRecord().initRecord();
    });

    await PerformanceMonitor.measureAsync('识别器初始化', () async {
      final llmUtils = LLMUtils();

      // 如果已经初始化，直接返回
      if (llmUtils.isInitialized || llmUtils.isInitializing) {
        return;
      }

      // 使用分步骤初始化，确保UI不被阻塞
      await llmUtils.preInitializeSST();
    });
  }
}
